<script setup lang="ts">
import { onMounted, reactive, h, ref } from 'vue';
import { useMessage, NCard, NDataTable, NButton, NSpace, NModal } from 'naive-ui';
import CreateProductAttr from './CreateProductAttr.vue';
import UpdateProductAttr from './UpdateProductAttr.vue';
import router from '../router';
import { getToken } from '../util/token';
import { defer } from '../util/decorator';
import { handleNoToken } from '../util/handler';
import { deleteProductAttributes, findAllProduct, ProductAttribute } from '../api/product';
import statusCode from '../api/statusCode';

const message = useMessage();

const productAttrs = reactive<ProductAttribute[]>([]);

const queryAllProduct = async () => {
  const token = getToken();
  if (!token) {
    handleNoToken(message);
    return [];
  }
  const currentId = +router.currentRoute.value.params.storeId;
  try {
    const resp = await findAllProduct({ storeId: currentId, token});

    if (resp.status === statusCode.SUCCESS) {
      return resp.data;
    } else if (resp.status === statusCode.QUERY_PRODUCT_FAILED) {
      // this store has no product.
      return [];
    } else {
      throw new Error(`错误码 ${resp.status}`);
    }
  } catch (error) {
    message.error("" + error);
    return [];
  }
};

const createColumns = ({
  handleUpdate,
  handleDelete
}: {
  handleUpdate: (rowData: ProductAttribute) => void,
  handleDelete: (rowData: ProductAttribute) => void
}) => {
  return [
    {
      title: '颜色',
      key: 'color'
    },
    {
      title: '单价',
      key: 'unitPrice'
    },
    {
      title: '库存',
      key: 'stock'
    },
    {
      key: 'actions',
      render(row: ProductAttribute) {
        return [
          h(
            NButton,
            {
              size: 'small',
              onClick: () => handleUpdate(row)
            },
            { default: () => '更新SKU信息' }
          ),
          h(
            NButton,
            {
              size: 'small',
              onClick: () => handleDelete(row),
              type: 'error'
            },
            { default: () => '删除SKU' }
          ),
        ]
      }
    }
  ]
};

const onDelete = async (productAttr: ProductAttribute) => {
  const token = getToken();
  if (!token) {
    handleNoToken(message);
    return;
  }
  try {
    const resp = await deleteProductAttributes({ attributeId: productAttr.attributeId, token });

    if (resp.status === statusCode.SUCCESS) {
      message.success(`成功删除商品SKU`, {
          duration: 1500,
          onAfterLeave: refreshList
      });
    } else {
      throw new Error(`错误码 ${resp.status}`);
    }
  } catch (error) {
    message.error("" + error);
  }
};

const columns = createColumns({
  handleUpdate: (row) => handleUpdateProductAttr(row),
  handleDelete: onDelete
});

const currentProductId = +router.currentRoute.value.params.productId;

const tableLoading = ref(true);

const createProductAttrTable = async () => {
  tableLoading.value = true;
  try {
    const products = await queryAllProduct();
    const product = products.find(
      productInfo => productInfo.productId === currentProductId
    );
    if (product) {
      productAttrs.length = 0;
      productAttrs.push(...product.attribute);
    } else {
      throw new Error(`No such product, productId: ${currentProductId}`);
    }
  } catch (error) {
    message.error('' + error);
  } finally {
    tableLoading.value = false;
  }
};
const handleCreateProductAttr = () => (showNewProductAttr.value = true);

const refreshList = createProductAttrTable;

const deferredCreateTable = defer(refreshList);
onMounted(createProductAttrTable);


const params = router.currentRoute.value.params;
const storeId = params.storeId;
const productId = +params.productId;

const showNewProductAttr = ref(false);

const tempAttribute = ref<ProductAttribute>({ imgPath: '', attributeId: -1, color: '', unitPrice: 0, stock: 0, productId });
const showUpdateProductAttr = ref(false);
const handleUpdateProductAttr = (attr: ProductAttribute) => {
  tempAttribute.value = attr;
  showUpdateProductAttr.value = true;
};
</script>

<template>
  <p>正在更改商店 {{ storeId }} 的商品 {{ productId }} SKU</p>
  <n-card title="商品SKU">
    <n-space
      vertical
      size="large"
    >
      <n-space size="medium">
        <n-button
          type="primary"
          @click="handleCreateProductAttr"
        >
          新建商品SKU
        </n-button>
        <n-button
          type="default"
          @click="deferredCreateTable"
        >
          刷新
        </n-button>
      </n-space>
      <n-data-table
        :loading="tableLoading"
        :columns="columns"
        :data="productAttrs"
        :pagination="{ pageSize: 10 }"
      />
    </n-space>
  </n-card>

  
  <n-modal
    v-model:show="showNewProductAttr"
    :mask-closable="false"
    class="modal"
  >
    <create-product-attr
      @close-product-attr="showNewProductAttr = false"
    />
  </n-modal>
  <n-modal
    v-model:show="showUpdateProductAttr"
    :mask-closable="false"
    class="modal"
  >
    <update-product-attr
      :attribute="tempAttribute"
      @close-product-attr="showUpdateProductAttr = false"
    />
  </n-modal>
</template>

<style scoped>
</style>
